<template>
  <div class="list-base-config">
    <je-panel>
      <template #tbar>
        <div class="header-button">
          <je-button type="text" @click="operateButton('save')"
            ><i class="fal fa-save"></i>保存</je-button
          >
          <je-button type="text" @click="operateButton('js')"
            ><i
              class="fas fa-bolt"
              :style="`color:${
                changeJsListener(funcStore.funcBean.FUNCINFO_GRIDJSLISTENER) ? '#F4CE4A' : '#8d98ab'
              }`"
            ></i
            >列表JS事件</je-button
          >
        </div>
      </template>
      <template #default>
        <div class="list-container">
          <div class="title"
            ><i class="jeicon jeicon-configure" style="margin-right: 6px"></i>核心配置</div
          >
          <je-form
            :model="formState"
            class="list-form-container"
            label-align="right"
            :colon="false"
            size="large"
            style="padding-bottom: 10px"
            autocomplete="off"
          >
            <je-row type="flex" justify="start">
              <je-col
                v-for="(item, index) in listFormData"
                :key="index"
                :span="item.layout == 'flex' ? '11' : '22'"
              >
                <je-form-item
                  :key="item.value"
                  :name="item.value"
                  v-bind="item.require ? validateInfos[item.value] : ''"
                  validate-type="tooltip"
                >
                  <template #label>
                    <i
                      v-if="item.unitTpl"
                      class="fas fa-question-circle"
                      style="color: #ebebeb"
                      :style="changeColor(item.unitTipShow)"
                      @click="clickTipView(item)"
                      @mouseenter="item.unitTipShow = true"
                      @mouseleave="item.unitTipShow = false"
                    />
                    <je-checkbox
                      v-if="item.type == 'checkbox'"
                      v-model:checked="state[item.checkedKey]"
                      :indeterminate="
                        item.value == 'FUNCINFO_GRIDHIDELINES'
                          ? state.indeterminate
                          : state.statisticsIndeterminate
                      "
                      style="margin-right: 2px"
                      @change="onCheckAllChange"
                    >
                    </je-checkbox>
                    <!-- <je-checkbox
                      v-if="item.type == 'checkbox' && item.value == 'FUNCINFO_GRIDHIDELINES'"
                      v-model:checked="checkAll"
                      :indeterminate="indeterminate"
                      @change="onCheckAllChange"
                    >
                    </je-checkbox> -->
                    <!-- <je-checkbox
                      v-if="item.type == 'checkbox' && item.value == 'FUNCINFO_STATISTICALSTRATEGY'"
                      v-model:checked="statistics"
                      :indeterminate="statisticsIndeterminate"
                      @change="onCheckAllChange"
                    >
                    </je-checkbox> -->
                    {{ item.label }}
                    <!-- <i
                      v-if="item.complete"
                      class="fas fa-flower"
                      style="color: rgb(235, 235, 235)"
                    ></i> -->
                  </template>
                  <je-form-item-rest>
                    <div v-if="item.type == 'input'">
                      <je-input
                        v-model:value="formState[item.value]"
                        :addon-after="item.suffix"
                        :placeholder="item.defaultValue"
                        :max-length="40"
                        allow-clear
                      >
                      </je-input>
                    </div>
                    <div v-if="item.type == 'inputNumber'" style="width: 100%">
                      <je-input-number
                        v-model:value="formState[item.value]"
                        :min="0"
                        step="5"
                        style="width: 100%"
                      >
                        <template v-if="item.suffix" #addonAfter>
                          {{ item.suffix }}
                        </template>
                      </je-input-number>
                    </div>
                    <div v-if="item.type == 'textarea'" :addon-after="item.suffix">
                      <je-textarea v-model:value="formState[item.value]" allow-clear :rows="4" />
                    </div>
                    <div v-if="item.type == 'switch'">
                      <je-switch v-model:value="formState[item.value]" />
                      <i class="remarks"> {{ item.remarks }}</i>
                    </div>
                    <div v-if="item.type == 'checkbox'" style="margin-top: 3px">
                      <je-checkbox-group
                        v-model:value="formState[item.value]"
                        :name="item.value"
                        :options="item.data"
                      />
                    </div>
                    <div v-if="item.type == 'radio'" style="margin-top: 4px">
                      <je-radio-group v-model:value="formState[item.value]" :options="item.data" />
                    </div>
                    <div v-if="item.type == 'select'">
                      <je-select
                        v-if="item.configInfo"
                        v-model:value="formState[item.value]"
                        :config-info="item.configInfo"
                      ></je-select>
                      <je-select
                        v-if="!item.configInfo"
                        v-model:value="formState[item.value]"
                        :options="item.data"
                      ></je-select>
                    </div>
                  </je-form-item-rest>
                </je-form-item>
              </je-col>
            </je-row>
          </je-form>
        </div>
      </template>
    </je-panel>
  </div>
</template>

<script>
  import { ref, defineComponent, reactive, watch, onMounted } from 'vue';
  import { Row, Col } from 'ant-design-vue';
  import {
    Form,
    Modal,
    Panel,
    Radio,
    Select,
    Checkbox,
    Button,
    Input,
    Switch,
    InputNumber,
  } from '@jecloud/ui';
  import { GetListBaseConfig, baseConfigSave } from '../../api/index';
  import { LIST_FORM_CONFIG } from './../../helper/constant';
  import { listenerEditorModal } from '@/helper/index.js';
  import { useFuncStore } from '@/store/func-store';

  const useForm = Form.useForm;

  export default defineComponent({
    name: 'ListBastCongfig',
    components: {
      JeButton: Button,
      JeRow: Row,
      JeCol: Col,
      JeForm: Form,
      JeFormItem: Form.Item,
      JeFormItemRest: Form.Item.Rest,
      JeInput: Input,
      JeSelect: Select,
      JeSwitch: Switch,
      JeCheckbox: Checkbox,
      JeCheckboxGroup: Checkbox.Group,
      JeRadioGroup: Radio.Group,
      JePanel: Panel,
      JeInputNumber: InputNumber,
      JeTextarea: Input.TextArea,
    },
    props: {
      recordData: {
        type: Object,
        required: true,
      },
    },
    setup(props) {
      const funcStore = useFuncStore();
      const formState = ref(funcStore.funcBean);
      // 表单校验必填项
      const rulesRef = {
        FUNCINFO_PAGESIZE: [
          {
            required: true,
            message: '该输入项为必填项',
          },
        ],
      };
      const { validateInfos, validate } = useForm(formState, rulesRef, {
        onValidate: (...args) => {},
      });
      // 移藏表格线的全选
      const state = reactive({
        indeterminate: true,
        statisticsIndeterminate: true,
        checkAll: false,
        statistics: false,
      });

      const menuActive = reactive({ show: '', recordData: props.recordData });

      //弹出关闭回调
      const btnClick = (obj) => {
        if (obj.type == 'close') {
          menuActive.show = '';
        }
      };

      const defaultData = ['right', 'bottom'];
      const statisticsData = ['single', 'all'];
      // watch
      watch(
        () => formState.value.FUNCINFO_GRIDHIDELINES,
        (newVal) => {
          let val = newVal ? newVal : [];
          val = val = Array.isArray(val) ? val : val.split(',');
          state.indeterminate = !!val.length && val.length < defaultData.length;
          state.checkAll = val.length === defaultData.length;
        },
      );

      watch(
        () => formState.value.FUNCINFO_STATISTICALSTRATEGY,
        (newVal) => {
          let val = newVal ? newVal : [];
          val = val = Array.isArray(val) ? val : val.split(',');
          state.statisticsIndeterminate = !!val.length && val.length < statisticsData.length;
          state.statistics = val.length === statisticsData.length;
        },
      );
      const methods = {
        getFuncValue(value) {
          return value;
        },
        clickTipView(item) {
          Modal.alert({
            content: item.unitTpl,
            title: item.label,
            icon: 'fal fa-info-circle',
            status: 'info',
            width: '460',
          });
        },
        // 当改变表单标签位置的时候，保存
        changeFromLocation(val) {
          formState.value.FUNCINFO_LABELALIGNMENT = val;
          const { FUNCINFO_FUNCCODE, tableCode, JE_CORE_FUNCINFO_ID } = formState.value;
          baseConfigSave({
            FUNCINFO_LABELALIGNMENT: val,
            FUNCINFO_FUNCCODE,
            tableCode,
            JE_CORE_FUNCINFO_ID,
          })
            .then((res) => {
              // message.success(res.message);
              console.log(res);
            })
            .catch((err) => {
              console.log(err);
            });
        },
        // 全选
        onCheckAllChange(e) {
          const id = e.target.id;
          const field = id?.split('form_item_')[1];
          if (field == 'FUNCINFO_GRIDHIDELINES') {
            formState.value.FUNCINFO_GRIDHIDELINES = e.target.checked ? 'right,bottom' : '';
            Object.assign(state, {
              indeterminate: false,
            });
          } else if (field == 'FUNCINFO_STATISTICALSTRATEGY') {
            formState.value.FUNCINFO_STATISTICALSTRATEGY = e.target.checked ? 'single,all' : '';
            Object.assign(state, {
              statisticsIndeterminate: false,
            });
          }
        },
        // 改变tip浮上去的颜色
        changeColor(flag) {
          if (flag) {
            return 'cursor:pointer;color: #3265F5';
          }
          return 'cursor:pointer;';
        },
        // 点击头部的按钮
        operateButton(type) {
          if (type == 'save') {
            validate()
              .then(() => {
                // 这边获取到保存的值，同时也要调取接口
                baseConfigSave(formState.value)
                  .then((res) => {
                    Modal.message(res.message, 'success');
                  })
                  .catch((err) => {
                    Modal.alert(err.message, 'error');
                  });
              })
              .catch((err) => {
                console.log('error', err);
                Modal.alert(err.message, 'error');
              });
          } else if (type == 'js') {
            listenerEditorModal({
              funcId: props.recordData.id,
              funcCode: props.recordData.code,
              funcName: props.recordData.text,
              eventType: 'grid',
              title: '列表JS事件',
              callback: (obj) => {
                formState.value.FUNCINFO_GRIDJSLISTENER = obj.data;
                funcStore.funcBean.FUNCINFO_GRIDJSLISTENER = obj.data;
              },
            });
          }
        },
        changeJsListener(data) {
          const parseData = data ? JSON.parse(data) : [];
          let eventType = false;
          parseData.forEach((item) => {
            if (item.fire == '1') {
              eventType = true;
            }
          });
          return eventType;
        },
        // 初始获取配置
        getListBaseConfigData() {
          const params = {
            type: 'column',
            pkValue: props.recordData.JE_CORE_FUNCINFO_ID,
          };
          GetListBaseConfig(params).then((res) => {
            delete res.$TABLE_CODE$;
            res.tableCode = 'JE_CORE_FUNCINFO';
            res.FUNCINFO_PAGEINFOALIGN = res.FUNCINFO_PAGEINFOALIGN || '';
            res.FUNCINFO_LABELALIGNMENT = res.FUNCINFO_LABELALIGNMENT || '1';
            res.FUNCINFO_CHILDREFRESH = res.FUNCINFO_CHILDREFRESH || '0';

            Object.assign(formState.value, res);
          });
        },
      };
      onMounted(() => {
        // 获取除数数据。不过这边还有待于商讨
        // methods.getListBaseConfigData();
      });

      return {
        funcStore,
        formState,
        ...methods,
        listFormData: ref(LIST_FORM_CONFIG),
        rulesRef,
        state,
        validateInfos,
        btnClick,
        menuActive,
      };
    },
  });
</script>
<style lang="less">
  .list-base-config {
    height: 100%;
    .ant-form-item-label {
      > label {
        display: inline-block !important;
        line-height: 32px;
        width: 200px !important;
      }
    }
    .ant-input-number {
      width: 100%;
    }
  }
</style>
<style lang="less" scoped>
  .list-base-config {
    // position: relative;

    .header-button {
      padding-left: 10px;
      background: #f7f9fc;
      height: 40px;
      line-height: 40px;
      padding-left: 5px;
      // border-top: 1px solid #f0f0f0;
      border-bottom: 1px solid #f0f0f0;

      .button-pointer {
        cursor: pointer;
      }
    }
    .list-container {
      // position: absolute;
      // top: 40px;
      // padding: 0 40px 30px;
      // width: 100%;
      // height: 100%;
      // overflow: scroll;
      .title {
        font-size: 18px;
        color: #3265f5;
        padding: 10px 0 10px 40px;
      }
      .remarks {
        padding-left: 10px;
        color: #3265f5;
      }
    }
  }
</style>
